<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Log;

class Metadatatype extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        return $this->fetch('index', ['list' => model('metadataType')->order('id asc')->select()]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $param['is_system'] = 1;
            if ($this->insert('metadataType', $param, false) === true) {
                insert_admin_log('添加了元数据类型');
                $this->success('添加成功', url('admin/metadatatype/index'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('save', ['metadataType' => model('metadataType')->order('id asc')->select()]);
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            if ($this->update('metadataType', $this->request->param(), false, input('_verify', true)) === true) {
                insert_admin_log('修改了元数据类型');
                $this->success('修改成功', url('admin/metadatatype/index'));
            } else {
                $this->error($this->errorMsg);
            }
        }
        return $this->fetch('save', [
            'data'     => model('metadataType')->where('id', input('id'))->find(),
            'metadataType' => model('metadataType')->order('id asc')->select(),
        ]);
    }

    public function del()
    {
        if ($this->request->isPost()) {
            if ($this->delete('metadataType', $this->request->param()) === true) {
                insert_admin_log('删除了元数据类型');
                $this->success('删除成功');
            } else {
                $this->error($this->errorMsg);
            }
        }
    }

    public function downloadOrUpload() {
        $type = model('metadataType')->where('id', input('id'))->find();
        if (!empty($type)) {
            $url = $type['template_url'];
            if (is_null($url)) {
                $this->error('上传暂未完成，请稍后', 'admin/metadatatype/index');
            }
            $file = '.' . $url;
            if (file_exists($file)) {
                ob_end_clean();
                header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Length: ' . filesize($file));
                header('Content-Disposition: attachment; filename=' . basename($file));
                readfile($file);
                $this->result('', 1, '获取地址成功');
            } else {
                throw new \Exception("文件不存在");
            }
        } else {
            $this->result('', 1, '没有地址');
        }
        $this->result('', 1, '上传成功');
    }

}
